﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<?php
require_once dirname(__FILE__).'/Authentication/AdminOnlyPageHeader.php';
require_once dirname(__FILE__).'/config/config.php';

$chkList = '';
foreach (ReadAllRoles() as $role)
{
    if (strlen($chkList) > 0)
        $chkList .= '</br>';
    $roleId = $role['RoleId'];
    $roleName =  utf8_encode($role['Name']);
    $chkList .= "<input type='checkbox' style='margin-right:10px;' name='chk_Roles' value='{$roleId}'>{$roleName}</input>";
}

?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SQL mokomasis puslapis</title>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <link type="text/css" rel="stylesheet" media="all" href="css/styles.css" />
<!--    <link rel="stylesheet" type="text/css" media="screen" href="css/redmond/jquery.ui.theme.css" />a    -->
    <link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery.ui.theme.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" /> 


    <link rel="stylesheet" type="text/css" media="screen" href="css/AdminPageStyle.css" />

    <script src="scripts/modernizr-2.0.4.js"></script>
    <script src="scripts/jquery-1.7.1.min.js" type="text/javascript"></script> 
<!--    <script src="scripts/jquery.jqGrid.src.js" type="text/javascript"></script>     -->
    <script src="scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
    <script src="scripts/grid.locale-lt.js" type="text/javascript"></script>
    <script src="scripts/grid.common.js" type="text/javascript"></script>
    <script src="scripts/grid.formedit.js" type="text/javascript"></script>
    <script src="scripts/jqDnR.js" type="text/javascript"></script>
    <script src="scripts/jqModal.js" type="text/javascript"></script>
</head>
<body>
    <div id="page-wrapper">
        <div id="page">
            <?php include('header1.php'); ?>
            <div class="content">
                <div class="left-side">
                    <?php include('menu-left.html'); ?>
                </div>
                <div class="right-side"> 
                    <h2>Administratoriaus puslapis</h2>
                    <table id="list2"></table>
                    <div id="pager2"></div>

                    <!-- Duomenų redagavimo/įvedimo forma -->
                    <form id="editForm" style="display:none;" action="/" data-mode="" >
                        <div class="SolidBorder form">
                          <table border="0">
                            <colgroup>
                                <col width="25%" />
                                <col width="50%" />
                                <col width="25%" />
                            </colgroup>
                            <thead>
                                <tr class="ui-jqdialog-title">
                                    <th colspan="2"><span id='FormTitle'>Naujas užrašas</span></th>
                                    <th>Rolės</th>
                                </tr>
                            </thead>
                            <tbody> 
                                <tr>
                                    <td>Paštas</td>
                                    <td class="padding">
                                        <input id="Email" type="text" name="eMail" style="width: 100%;" />
                                    </td>
                                    <td rowspan="5">
                                        <div id="AllRoles" class="scroll">
                                            <?php echo $chkList ?>
                                        </div>
                                    </td>
                                </tr>
                                <tr>  
                                    <td>Vardas, Pavardė</td> 
                                    <td class="padding">
                                        <input id="UserName" type="text" name="userName" style="width: 100%;" />
                                    </td>
                                </tr>
                                <tr>  
                                    <td>Aktyvus</td>
                                    <td>
                                        <input id="IsActive" type="checkbox" name="isActive" value="isActive">
                                    </td> 
                                </tr>
                                <tr>  
                                    <td>Administratorius</td>
                                    <td>
                                        <input id="IsAdmin" type="checkbox" name="isAdmin" value="isAdmin">
                                    </td> 
                                </tr>
                                <tr>
                                    <td  colspan="2">
                                        <button type="button" class="DataEditButton" style="margin-left: 5px;"
                                                onClick= "return SubmitInsert(this);">Taip</button>
                                        <button type="button" class="DataEditButton" onClick= "return CancelInsert(this);">Ne</button>
                                    </td>
                                </tr>
                            </tbody>
                          </table>
                        </div>
                    </form>

                 </div>
            </div>
            <?php include('footer.html'); ?>
        </div>
    </div>
    <input type="hidden" id="hid" />

    <script type="text/javascript" src="scripts/navigacija.js"></script> 	
    <script type="text/javascript">
    <!--
        $(document).ready(function(){
            var dataServerUrl = '<?php echo "{$RootDirectoryUri}/Authentication/DataServer.php?q=2";?>';
            jQuery("#list2").jqGrid({
                url: dataServerUrl,
                datatype: "xml",
                mtype: 'GET',
                colNames:['Paštas','Vardas, Pavardė', 'Aktyvus', 'Admin.','Rolės'],
                colModel:[
                    {name:'Email',index:'eMail', width:120, align:"left", sortable:false, editable:false, search:false}, 
                    {name:'Name',index:'Name', width:150, align:"left", sortable:true, editable:false, search:true, edittype:'text',
                        searchoptions: {sopt: ['eq','ne', 'bw','bn','in','ni','ew','en']}},
                    {name:'IsActive',index:'IsActive', width:30, align:"center", sortable:true, editable:false, search:true, edittype:'text',
                        stype: 'select', searchoptions: {sopt: ['eq','ne'], value:'1:Taip;0:Ne'}},
                    {name:'IsAdmin',index:'IsAdmin', width:30, align:"center", sortable:true, editable:false, search:true, edittype:'text',
                        stype: 'select', searchoptions: {sopt: ['eq','ne'], value:'1:Taip;0:Ne'}},
                    {name:'AllRoles',index:'allRoles', width:100, align:"left", sortable:false, editable:false, search:true, edittype:'text',
                        searchoptions: {sopt: ['cn','nc']}}	
                    ],
                width: 800,
                height: 300,
                viewrecords: true,
                gridview: true,
                rowNum:10,
                rowList:[10,20,30],
                pager: '#pager2',
                sortname: 'name',
                sortorder: "ascending ",
                caption:"SQL pamokų vartotojai",
                loadError: function(xhr, status, error) {
                    alert('Klaida: ' + status);
                }
            });
            jQuery("#list2").jqGrid('navGrid','#pager2',{edit:false, add:false, del:false})
                .navButtonAdd('#pager2', {
                   caption: "", 
                   title:"Naujas užrašas", 
                   buttonicon:"ui-icon-plusthick", 
                   onClickButton: function(){ 
                       $('#editForm').attr("data-mode", "insert");
                       $('#editForm span#FormTitle').text('Užpildykite naują užrašą')
                       ClearDialog();
                       $('#editForm').show();
                   }, 
                   position:"last"
                }).navButtonAdd('#pager2', {
                    caption: "", 
                    title: "Taisyti užrašą",
                    buttonicon: "ui-icon-pencil",
                    onClickButton: function(){ 
                       $('#editForm').attr("data-mode", "edit");
                       $('#editForm span#FormTitle').text('Pataisykite užrašo reikšmes')
                       FillDialog();
                       $('#editForm').show();
                    },
                    position:"last"
                }).navButtonAdd('#pager2', {
                    caption: "", 
                    title: "Trinti užrašą",
                    buttonicon: "ui-icon-closethick",
                    onClickButton: function(){ 
                        $('#editForm').attr("data-mode", "delete");
                        $('#editForm span#FormTitle').text('Patvirtinkite užrašo trynimą')
                        FillDialog();
                        $('#editForm').show();
                    },
                    position:"last"
                });
        });
        $.extend($.jgrid.search,
            {closeAfterSearch: true, closeAfterReset: true, closeOnEscape: true}); 

        function ClearDialog()
        {
            $('#editForm input:text').val('');
            $('#editForm input:checkbox').attr('checked', false);
        }

        function FillDialog()
        {
            var myGrid = $('#list2')
            var selRowId = myGrid.jqGrid ('getGridParam', 'selrow');
            if (selRowId)
            {
                var selRow = myGrid.getRowData(selRowId);
                $('#editForm input#Email').val(selRow['Email']);
                $('#editForm input#UserName').val(selRow['Name']);
                if (selRow['IsActive']) // Tuščia eilutė - vartotojas aktyvus
                    $('#editForm input#IsActive').attr('checked', false);
                else
                    $('#editForm input#IsActive').attr('checked', true);
                if (selRow['IsAdmin']) // Tuščia eilutė - eilinis vartotojas
                    $('#editForm input#IsAdmin').attr('checked', true);
                else
                    $('#editForm input#IsAdmin').attr('checked', false);

                var selectedRoles = (selRow['AllRoles']).split(" ");
                $('#editForm div#AllRoles input[type="checkbox"]').each(function() {
                    var chkBox = $(this);
                    var roleCode = chkBox.val();
                    var position = selectedRoles.indexOf(roleCode);
                    chkBox.attr('checked', position >= 0);
                });
            }
            else
                alert("Pasirinkite koreguojamą eilutę paspausdami ją su pele.");
        }

        function SubmitInsert(activeButton) {
            var postData = CollectData();
            var isValidData = ValidateData(postData);
            if (isValidData)
            {
                $.ajax({
                    type: "POST",
                    url: "Authentication/PostUserData.php",
                    data: postData,
                    cache: false,
                    success: function(data){
                        var json = $.parseJSON(data);
                        var parameters = { 
                                Email: json.Email, Name: json.Name, IsActive: json.IsActive ? '' : 'Ne', 
                                IsAdmin: json.IsAdmin ? 'Taip' : '', AllRoles: json.AllRoles
                            };
                        if (json.operation == 'insert')
                           jQuery("#list2").jqGrid('addRowData', json.Email, parameters, 'last');
                        else if (json.operation == 'delete')
                           jQuery("#list2").jqGrid('delRowData', json.Email);
                        else
                           jQuery("#list2").jqGrid('setRowData', json.Email, parameters);
                    }
                }).fail(function(jqXHR, textStatus, errorThrown) { 
                    alert(errorThrown); 
                }).always(function() {
                    $('#editForm').hide();
                });
            }
            return false;
        }

        function CancelInsert(activeButton) {
            $('#editForm').hide();
            return false;
        }

        function ValidateData(postData)
        {
            if (!postData.Email)
            {
                alert("Nurodykite elektroninį paštą.")
                return false;
            }
            if (!postData.Name)
            {
                alert("Nurodykite vardą ir pavardę.")
                return false;
            }
            if ((postData.IsActive == "1") && (postData.IsAdmin == "0") && !postData.AllRoles)
            {
                alert("Aktyviam eiliniam vartotojui būtina nurodyti bent vieną rolę.")
                return false;
            }
            return true;
        }

        function CollectData()
        {
            var checkedRoles = [];
            $('#editForm table tbody tr td div#AllRoles input[type="checkbox"]:checked').each(function() {
                checkedRoles.push($(this).val());
            });

            var rzlt = { 
                mode: $('#editForm').attr("data-mode"),
                Email: $('#editForm table tbody tr td input#Email').val(),
                Name: $('#editForm table tbody tr td input#UserName').val(),
                IsActive: $('#editForm table tbody tr td input#IsActive').is(':checked') ? "1" : "0",
                IsAdmin: $('#editForm table tbody tr td input#IsAdmin').is(':checked') ? "1" : "0",
                AllRoles: checkedRoles.join(' ')
            };
            return rzlt;
        }
    //-->
    </script>
</body>
</html>
